package forminrecipe.GUI;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import forminrecipe.core.Core;
import forminrecipe.data.*;

public class ListPanel extends JPanel {
	private JList listJList;
	private JScrollPane listScrollPane;
	private DefaultListModel listData =new DefaultListModel();
	private BoxLayout listLayout;
	private JButton clearButton;
	private JButton printButton;
	private JButton addButton;

	private JTextField addTextField;
	private JPanel buttonPanel;
	private JPanel addPanel;
	
	private Core coreRef;
	public ListPanel(Core core){
		coreRef = core;
		listLayout=new BoxLayout(this, BoxLayout.Y_AXIS);
		this.setLayout(listLayout);
		
		buttonPanel=new JPanel();
		addPanel=new JPanel();
		clearButton=new JButton(constants.CLEAR_LIST_BUTTON_TEXT);
		printButton=new JButton("Print");
		
		addButton=new JButton(constants.ADD_TO_LIST_BUTTON_TEXT);
		addButton.addActionListener(new MyAction());
		addTextField=new JTextField(30);
		
		this.add(new JLabel("Shopping List:"));
		listJList = new JList(listData);
		listScrollPane=new JScrollPane(listJList);
		listScrollPane.setPreferredSize(new Dimension(100,200));
		this.add(listScrollPane);
		
		listJList.setModel(listData);
		
		addPanel.add(addTextField);
		addPanel.add(addButton);
		buttonPanel.add(clearButton);
		buttonPanel.add(printButton);
		this.add(addPanel);
		this.add(buttonPanel);
		
	}
	
	public void addItemToList(String item){
		listData.addElement(item);
		listJList.setModel(listData);
	}
	public void clearList(){
		listData.clear();
		listJList.setModel(listData);
	}
	
	public class MyAction implements ActionListener{
	    public void actionPerformed(ActionEvent e){
	      String text = (String)e.getActionCommand();
	      
	      if(text == constants.ADD_TO_LIST_BUTTON_TEXT){
	    	  addItemToList(addTextField.getText());
	    	  coreRef.addListItemDBM(addTextField.getText());
	    	  addTextField.setText("");
			
	      }else if(text==constants.CLEAR_LIST_BUTTON_TEXT){
	    	  clearList();
	      }
	    }
	}
}
